#include<stdio.h>
#include<string.h>                                                              
#include<unistd.h>
#include<pthread.h>
#include<fcntl.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<stdlib.h>
#include<sys/epoll.h>

#define SERVERPORT 8000
#define BUFSIZE 1024
#define EVENTSIZE 1025

int listen_bind_sock(int port)
{
    int lfd=socket(AF_INET,SOCK_STREAM,0);
    if(lfd==-1)
    {
        perror("socket error");
        exit(1);
    }
    struct sockaddr_in serveraddr;
    serveraddr.sin_family=AF_INET;
    serveraddr.sin_port=htons(SERVERPORT);
    serveraddr.sin_addr.s_addr=0;
    bind(lfd,(struct sockaddr*)&serveraddr,sizeof(serveraddr));
    listen(lfd,64);
    return lfd;
}

int main(int argc, char* argv[])
{
    int lfd=listen_bind_sock(SERVERPORT);
    char buf[BUFSIZE];
    int wait_ret;
    int read_ret;
    int cfd;

    int epfd=epoll_create(64);
    if(epfd==-1)
    {
        perror("epoll_create error");
        exit(1);
    }

    struct epoll_event events[EVENTSIZE];

    struct epoll_event event;
    event.events=EPOLLIN;
    event.data.fd=lfd;
    epoll_ctl(epfd,EPOLL_CTL_ADD,lfd,&event);

    while(1)
    {
        wait_ret=epoll_wait(epfd,events,EVENTSIZE,-1);//返回值为成功存入数组中的文件描述符个数
        if(wait_ret==-1)
        {
            perror("epoll_wait error");
            exit(1);
        }
        for(int i=0;i<wait_ret;i++)
        {
            if(events[i].events & EPOLLIN)
            {
                if(events[i].data.fd==lfd)
                {
                    cfd=accept(lfd,NULL,NULL);
                    if(cfd==-1)
                    {
                        perror("accept error");
                        exit(1);
                    }
                    printf("客户端建立连接\n");
                    event.events=EPOLLIN;
                    event.data.fd=cfd;
                    epoll_ctl(epfd,EPOLL_CTL_ADD,cfd,&event);
                }
                else
                {
                    read_ret=read(events[i].data.fd,buf,BUFSIZE);
                    if(read_ret==-1)
                    {
                        perror("read error");
                        exit(1);
                    }
                    else if(read_ret==0)
                    {
                        printf("有客户端退出\n");
                        close(events[i].data.fd);
                        epoll_ctl(epfd,EPOLL_CTL_DEL,events[i].data.fd,NULL);
                    }
                    else 
                    {
                        write(events[i].data.fd,buf,read_ret);
                        printf("*********************\n");
                        write(STDOUT_FILENO,buf,read_ret);
                        printf("*********************\n");
                    }
                }
            }
        }
    }
    return 0;
}


